package com.ark.frigate.mybatis.utils;

import com.ark.frigate.mybatis.config.DataSourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 主要负责连接数据库
 *
 * @author Along
 */
public class DbConn {

    private static Logger logger = LoggerFactory.getLogger(DbConn.class);

    private static DataSourceConfig config;

    private static Connection CONN;

    /**
     * 初始化连接
     *
     * @return Connection 返回连接
     * @throws ClassNotFoundException 驱动加载异常
     * @throws SQLException           SQL异常
     */
    public static Connection getConn() throws ClassNotFoundException, SQLException {
        if (CONN == null) {
            if (config == null) {
                throw new RuntimeException("数据库连接没有配置.");
            }
            Class.forName(config.getDriverClass());
            CONN = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
        }
        return CONN;
    }

    public static void close() {

        if (CONN != null) {
            try {
                CONN.close();
            } catch (SQLException e) {
                logger.error("Database close Exception {}!", e.getMessage());
            }
        }
    }

    public static DataSourceConfig getConfig() {
        return config;
    }

    public static void setConfig(DataSourceConfig config) {
        DbConn.config = config;
    }
}
